#!/usr/bin/python

import RPi.GPIO as GPIO
import mosquitto
import time
import os
import sys

room_temp={}

def on_message(mosq, msg):
    global room_temp
    if(msg.topic=="data/heatingReset"):
        room_temp={}
        return
    room_temp[msg.topic]=float(msg.payload)
    avg=0
    for room in room_temp.keys():
        avg=avg+room_temp[room]
    avg=avg/len(room_temp.keys())
    if avg < 18: listener.publish('control/heating','low')
    else:
        if avg > 20: listener.publish('control/heating','high')

def on_connect(mosq, rc):
    if rc==0: 
        print("Mosquitto connected ok")
        listener.subscribe("temp/+", 1)
        listener.subscribe("data/heatingReset", 1)
    else:
        listener.connect("KitchenPI.home")

def on_disconnect(mosq):
    print("Disconnected")

def on_subscribe(mosq, mid, rc):
    print("Subscribed ok")

listener = mosquitto.Mosquitto(os.uname()[1]+"-"+str(os.getpid()))
print("Created client")
listener.on_connect = on_connect
listener.on_disconnect = on_disconnect
listener.on_message = on_message
print("Defined callbacks")

while 1==1:
    while listener.loop()==0:
        time.sleep(5)
    time.sleep(5)
    listener.connect("KitchenPI.home")
